<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { ResponseApi, LoginForm } from '@/utils/type'

import { useAuthStore } from '@/stores/useAuthStore'

// 定义表单数据类型




// 响应式数据
const username = ref('')
const password = ref('')
const router = useRouter() 

// 表单提交处理
const onSubmit = async (values: LoginForm) => {
  try {

    // 获取临时令牌
    let tempToken = await getTempToken(username.value)
    if (tempToken == "") {
      console.log("获取临时令牌失败");
      return;
    }
    // 加密密码
    let passwordValue = await encryptPassword(password.value)

    const res = await request.post('/auth/login', {
      username: username.value,
      password: passwordValue,
      loginType: 0,
      tempToken
    })
    const token  = res.data

    // 使用 Pinia 存储 token 并持久化到 localStorage
    const authStore = useAuthStore()
    authStore.setToken(token, username.value)

    // 跳转首页
    router.push('/')
  } catch (error) {
    console.error(error)
  }
}
/**
 * 加密密码
 */
const encryptPassword = async (password: string) => {
  const res: ResponseApi = await request.get(`/auth/encrypt?data=${password}`)
  if (res.code == 200) {
    return res.data;
  }
  console.error(res.message);
  return "";
}
/**
 * 获取临时令牌
 * @param username  用户名
 */
const getTempToken = async (username: string) => {

  try {
    const res: ResponseApi = await request.get(`/auth/tempToken?username=${username}`)
    console.log(res);
    if (res.code == 200) {
      return res.data;
    }
    console.error(res.message);
    return "";

  } catch (error) {
    console.error(error)
    return "";
  }
}
</script>

<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]" />
      <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>

</template>

<style scoped></style>
